import os
import shutil
import time
from tkinter import Tk, filedialog
import sys

# 作者：知夏秋天
# gitee仓库：https://gitee.com/ZhixiaAutumn/simple-tools

# 仅支持单文件夹和单层的路径
# 先匹配图片名再匹配引用路径 例如：xxx 和 images/xxx
# 未匹配到同名，移动路径为：时间戳_noNameImg
# 未匹配到路径，移动路径为：时间戳_noPathImg

def get_md_file():
    root = Tk()
    root.withdraw()  # 隐藏主窗口
    file_path = filedialog.askopenfilename(
        title="清理 md 中无引用图片的小工具（仅移动）",
        filetypes=[("Markdown files", "*.md")]
    )
    return file_path

def get_images_directory():
    root = Tk()
    root.withdraw()  # 隐藏主窗口
    directory = filedialog.askdirectory(
        title="选择要对比的图片文件夹（默认images未找到）"
    )
    return directory

def get_images_in_directory(directory):
    return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]

def find_unreferenced_imagesV1(md_content, images):
    images_set = set(images)
    return [image for image in images_set if image not in md_content]

def find_unreferenced_imagesV2(md_content, images, prefix):
    images_set = set(images)
    return [image for image in images_set if f"{prefix}/{image}" not in md_content]

def move_unreferenced_images(unreferenced_images, images_dir, new_dir):
    if not os.path.exists(new_dir):
        os.makedirs(new_dir)
    for image in unreferenced_images:
        source_path = os.path.join(images_dir, image)
        destination_path = os.path.join(new_dir, image)
        if os.path.exists(source_path):
            shutil.move(source_path, destination_path)

def main():
    try:
        md_file_path = get_md_file()
        if not md_file_path:
            print("没有选择任何文件")
            return

        with open(md_file_path, 'r', encoding='utf-8') as file:
            md_content = file.read()

        imgFileName = 'images'
        images_dir = os.path.join(os.path.dirname(md_file_path), imgFileName)
        if not os.path.exists(images_dir):
            images_dir = get_images_directory()
        if not images_dir or not os.path.exists(images_dir):
            print("没有选择对比图片文件夹")
            return

        timestamp = int(time.time())
        imgFileName = os.path.basename(images_dir)
        images = get_images_in_directory(images_dir)

        unreferenced_imagesV1 = find_unreferenced_imagesV1(md_content, images)
        if unreferenced_imagesV1:
            new_dir = os.path.join(os.path.dirname(md_file_path), f'{timestamp}_noNameImg')
            move_unreferenced_images(unreferenced_imagesV1, images_dir, new_dir)
            print(f"未匹配到同名的图片，已移动到 {new_dir}")

        unreferenced_imagesV2 = find_unreferenced_imagesV2(md_content, list(set(images) - set(unreferenced_imagesV1)), imgFileName)
        if unreferenced_imagesV2:
            new_dir = os.path.join(os.path.dirname(md_file_path), f'{timestamp}_noPathImg')
            move_unreferenced_images(unreferenced_imagesV2, images_dir, new_dir)
            print(f"未匹配到路径的图片，已移动到 {new_dir}")
        else:
            print("没有未引用或未匹配的图片")

        # 延迟3秒后关闭程序
        print("程序将在3秒后关闭...")
        time.sleep(3)
    except Exception as e:
        print(f"发生错误: {e}")
        print("程序将在3秒后关闭...")
        time.sleep(3)
    finally:
        sys.exit()

if __name__ == "__main__":
    main()
